package com.flashcash.solu.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.ReplacementTransformationMethod;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.flashcash.solu.R;

import java.util.regex.Pattern;

/**
 * 选择选项 状态：错误、已选内容，默认
 * Created on 2019/5/2 下午9:49.
 */

public class MyEditTextView extends LinearLayout {

    private TextView top;
    //    private TextView hint;
    private TextView error;
    private EditText content;
    private View defaultLine;
    private View errorLine;
    private ImageView iv;
    private LinearLayout item;
    private Pattern pattern;//数据正确正则
    private Pattern inputPattern;//输入正则
    private boolean nullable;//可为空
    private boolean firstLoad = true;
    private String beforeText;//初始化

    public MyEditTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.widget_my_edit_text_view, this);

        item = findViewById(R.id.ll_item);
        top = findViewById(R.id.tv_top);
//        hint = findViewById(R.id.tv_hint);
        error = findViewById(R.id.tv_error);
        content = findViewById(R.id.et_content);
        defaultLine = findViewById(R.id.default_line);
        errorLine = findViewById(R.id.error_line);
        iv = findViewById(R.id.iv_icon);

        // 获得自定义属性
        TypedArray typedArray = context.obtainStyledAttributes(attrs,
                R.styleable.MyEditTextView);

        nullable = typedArray.getBoolean(R.styleable.MyEditTextView_EtNullable, false);
        top.setText(typedArray.getText(R.styleable.MyEditTextView_EtTopString));
//        hint.setText(typedArray.getText(R.styleable.MyEditTextView_EtHintString));
        content.setHint(typedArray.getText(R.styleable.MyEditTextView_EtHintString));
        if (!nullable) {
            error.setText(typedArray.getText(R.styleable.MyEditTextView_EtErrorString));
            try {
                pattern = Pattern.compile(typedArray.getString(R.styleable.MyEditTextView_EtLegalPattern));
                inputPattern = Pattern.compile(typedArray.getString(R.styleable.MyEditTextView_EtLegalInputPattern));
            } catch (Exception e) {

            }
        }
        boolean showIcon = typedArray.getBoolean(R.styleable.MyEditTextView_EtIconVisibility, false);
        if (showIcon) {
            content.setEnabled(false);
        }
        iv.setVisibility(showIcon ? VISIBLE : INVISIBLE);

        typedArray.recycle();

        content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                Log.d("beforeTextChanged", "1111");
                beforeText = s.toString();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.d("onTextChanged", "2222");
            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.d("afterTextChanged", "2222");
                if (s.toString().equals(beforeText)) {
                    return;
                }
                checkStatus();
            }
        });
        content.setOnFocusChangeListener((v, hasFocus) -> {
            Log.d("test", "focus");
            if (firstLoad) {//初始化时
                firstLoad = false;
                return;
            }
            checkStatus();
        });
        item.setOnClickListener(v -> {
            top.setVisibility(VISIBLE);
//            hint.setVisibility(GONE);
//            hint.setSelected(false);
//            content.setVisibility(VISIBLE);
            content.setFocusable(true);
            content.setFocusableInTouchMode(true);
            content.requestFocus();
            content.setSelection(content.getText().toString().length());
            defaultLine.setVisibility(VISIBLE);
            errorLine.setVisibility(GONE);
            error.setVisibility(GONE);
            if (mItemOnClickListener != null) {
                mItemOnClickListener.onClick();
            }

            if (TextUtils.isEmpty(content.getText())) {
                content.setText("");
            }

        });
    }

    private void checkStatus() {
        if (nullable) {
            if (TextUtils.isEmpty(content.getText().toString())) {
                setDefaultStatus();
            } else {
                setSuccessStatus();
            }
            return;
        }

        if (TextUtils.isEmpty(content.getText().toString())) {
            setErrorStatus();
            return;
        }

        Pattern myPattern = inputPattern != null ? inputPattern : pattern;
        if (myPattern == null) {
            setSuccessStatus();
        } else {
            boolean result = myPattern.matcher(content.getText().toString()).matches();
            if (result) {
                setSuccessStatus();
            } else {
                setErrorStatus();
            }
        }
    }

    private void setDefaultStatus() {
        top.setVisibility(GONE);
        content.setSelected(false);
        defaultLine.setVisibility(VISIBLE);
        errorLine.setVisibility(GONE);
        error.setVisibility(GONE);
    }

    private void setErrorStatus() {
        top.setVisibility(GONE);
        content.setSelected(true);
        defaultLine.setVisibility(GONE);
        errorLine.setVisibility(VISIBLE);
        error.setVisibility(VISIBLE);
    }

    private void setSuccessStatus() {
        top.setVisibility(VISIBLE);
//        hint.setVisibility(GONE);
//        hint.setSelected(false);
//        content.setVisibility(VISIBLE);
        content.setSelected(false);
        defaultLine.setVisibility(VISIBLE);
        errorLine.setVisibility(GONE);
        error.setVisibility(GONE);
    }

    public void setText(String text) {
        if (null == text) {
            return;
        }
        Log.i("setText", text);
        content.setText(text);
    }

    public String getText() {
        return content.getText().toString();
    }

    public EditText getEditText() {
        return content;
    }

    public interface ItemOnClickListener {
        void onClick();
    }

    private ItemOnClickListener mItemOnClickListener;

    public void setItemOnClickListener(ItemOnClickListener itemOnClickListener) {
        mItemOnClickListener = itemOnClickListener;
    }

    /**
     * 获取校验值
     *
     * @return
     */
    public boolean checkLegal() {
        if (nullable) {
            return true;
        }

        if (inputPattern != null && !inputPattern.matcher(content.getText().toString()).matches()) {
            return false;
        }
        return pattern == null || pattern.matcher(content.getText().toString()).matches();
    }

    public void setMyTransformationMethod(ReplacementTransformationMethod replacementTransformationMethod) {
        content.setTransformationMethod(replacementTransformationMethod);
    }

}
